If, Else, Else If, and Switch in Dart
Conditional statements are an important part of Dart programming because they allow a program to make decisions based on different conditions. In JustAcademy's Flutter curriculum, Dart Programming Fundamentals includes control statements such as if, loops, and switch. :contentReference[oaicite:0]{index=0}
These concepts are especially useful when developing Flutter applications because application behavior often depends on user input, authentication status, selected options, product availability, permissions, and other conditions.
1. What Are Conditional Statements?
Conditional statements execute different blocks of code depending on whether a condition is true or false.
For example:
int age = 20;
if (age >= 18) {
print("You are an adult.");
}
Here, the message is printed only when the condition age >= 18 is true.
2. Types of Conditional Statements in Dart
- if statement
- if-else statement
- else-if ladder
- Nested if
- switch statement
- Ternary operator for simple conditions
3. The if Statement
The if statement executes a block of code only when its condition evaluates to true.
Syntax
if (condition) {
// code to execute
}
Example
int age = 25;
if (age >= 18) {
print("You can vote.");
}
Since age is 25, the condition is true and the message is displayed.
Another Example
double marks = 85;
if (marks >= 80) {
print("Excellent performance!");
}
4. if with Comparison Operators
The if statement can be combined with comparison operators such as ==, !=, >, <, >=, and <=.
int price = 1000;
if (price > 500) {
print("The product is expensive.");
}
Using ==
String role = "admin";
if (role == "admin") {
print("Admin dashboard available.");
}
5. if with Logical Operators
Multiple conditions can be combined using logical operators such as &&, ||, and !.
Using AND (&&)
int age = 25;
bool hasId = true;
if (age >= 18 && hasId) {
print("Access granted.");
}
Using OR (||)
String role = "admin";
if (role == "admin" || role == "manager") {
print("You can access the dashboard.");
}
Using NOT (!)
bool isBlocked = false;
if (!isBlocked) {
print("User can continue.");
}
6. The if-else Statement
The if-else statement provides two possible execution paths:
- If the condition is true, the
if block executes.
- If the condition is false, the
else block executes.
Syntax
if (condition) {
// code when condition is true
} else {
// code when condition is false
}
Example
int age = 16;
if (age >= 18) {
print("You are eligible.");
} else {
print("You are not eligible.");
}
Login Example
String username = "admin";
String password = "1234";
if (username == "admin" && password == "1234") {
print("Login successful");
} else {
print("Invalid username or password");
}
7. else if Statement
The else if statement is used when there are multiple conditions to check.
Syntax
if (condition1) {
// code
} else if (condition2) {
// code
} else if (condition3) {
// code
} else {
// default code
}
8. Student Grade Example
int marks = 82;
if (marks >= 90) {
print("Grade A+");
} else if (marks >= 80) {
print("Grade A");
} else if (marks >= 70) {
print("Grade B");
} else if (marks >= 60) {
print("Grade C");
} else {
print("Fail");
}
Dart checks the conditions from top to bottom. Once a matching condition is found, its block is executed.
9. Age Category Example
int age = 35;
if (age < 13) {
print("Child");
} else if (age < 20) {
print("Teenager");
} else if (age < 60) {
print("Adult");
} else {
print("Senior Citizen");
}
10. Discount Example
double amount = 7500;
if (amount >= 10000) {
print("20% discount");
} else if (amount >= 5000) {
print("10% discount");
} else if (amount >= 2000) {
print("5% discount");
} else {
print("No discount");
}
11. Importance of Condition Order
The order of conditions is important in an else if ladder. Dart evaluates the conditions from top to bottom.
int marks = 95;
if (marks >= 40) {
print("Pass");
} else if (marks >= 90) {
print("Excellent");
}
The first condition is already true, so the second condition will never be reached. A better approach is to check the more specific or higher range first.
int marks = 95;
if (marks >= 90) {
print("Excellent");
} else if (marks >= 40) {
print("Pass");
} else {
print("Fail");
}
12. Nested if Statement
An if statement inside another if statement is called a nested if statement.
int age = 25;
bool hasLicense = true;
if (age >= 18) {
if (hasLicense) {
print("You can drive.");
} else {
print("You need a driving license.");
}
} else {
print("You are too young to drive.");
}
13. The switch Statement
The switch statement is useful when you need to compare one value against multiple possible cases.
Basic Syntax
switch (value) {
case value1:
// code
break;
case value2:
// code
break;
default:
// default code
}
14. Simple switch Example
String day = "Monday";
switch (day) {
case "Monday":
print("Start of the week");
break;
case "Friday":
print("Almost weekend");
break;
case "Sunday":
print("Weekend");
break;
default:
print("Regular day");
}
15. switch with Numbers
int option = 2;
switch (option) {
case 1:
print("Home");
break;
case 2:
print("Profile");
break;
case 3:
print("Settings");
break;
default:
print("Invalid option");
}
16. switch for a Menu
String choice = "profile";
switch (choice) {
case "home":
print("Opening Home");
break;
case "profile":
print("Opening Profile");
break;
case "settings":
print("Opening Settings");
break;
case "logout":
print("Logging out");
break;
default:
print("Unknown option");
}
17. default in switch
The default case runs when none of the available cases matches the switch value.
int number = 10;
switch (number) {
case 1:
print("One");
break;
case 2:
print("Two");
break;
default:
print("Other number");
}
18. Modern switch Expressions
Modern Dart also supports switch expressions, which can be useful when a value needs to be selected based on a pattern or case.
String grade = "A";
String result = switch (grade) {
"A" => "Excellent",
"B" => "Good",
"C" => "Average",
_ => "Needs improvement"
};
print(result);
The _ pattern can act as a catch-all case in this style of switch expression.
19. if-else vs switch
| if-else |
switch |
| Useful for conditions and ranges |
Useful for matching multiple possible values |
| Works well with complex logical conditions |
Works well with multiple cases |
| Can use operators such as >, <, >= |
Useful for specific matching cases |
| Good for validation and comparisons |
Good for menus, options, commands, and states |
20. if vs if-else vs else-if vs switch
| Statement |
Purpose |
Example Use |
| if |
Execute code when one condition is true |
Check login status |
| if-else |
Choose between two paths |
Pass or fail |
| else-if |
Choose between multiple conditions |
Grades or discount levels |
| switch |
Match one value against multiple cases |
Menu or user role |
21. Conditional Statements in Flutter
Conditional logic is frequently used inside Flutter applications to decide what should be displayed or what action should occur. JustAcademy's Flutter curriculum combines Dart fundamentals with widgets, UI development, navigation, forms, API integration, Firebase, and application projects. :contentReference[oaicite:1]{index=1}
Example: Showing Different Messages
bool isLoggedIn = true;
if (isLoggedIn) {
print("Welcome back!");
} else {
print("Please log in.");
}
Example: User Role
String role = "admin";
if (role == "admin") {
print("Show admin dashboard");
} else if (role == "editor") {
print("Show editor dashboard");
} else if (role == "user") {
print("Show user dashboard");
} else {
print("Unknown role");
}
22. E-Commerce Example
double cartTotal = 6500;
bool isMember = true;
if (cartTotal >= 5000 && isMember) {
print("Apply premium discount");
} else if (cartTotal >= 5000) {
print("Apply standard discount");
} else {
print("No discount available");
}
23. Login Validation Example
String email = "[email protected]";
String password = "123456";
if (email.isEmpty || password.isEmpty) {
print("Please fill all fields");
} else if (password.length < 6) {
print("Password must contain at least 6 characters");
} else {
print("Login information is valid");
}
24. Student Result Example
int marks = 76;
if (marks >= 90) {
print("Grade A+");
} else if (marks >= 80) {
print("Grade A");
} else if (marks >= 70) {
print("Grade B");
} else if (marks >= 60) {
print("Grade C");
} else if (marks >= 40) {
print("Grade D");
} else {
print("Fail");
}
25. Day Selection Using switch
int day = 3;
switch (day) {
case 1:
print("Monday");
break;
case 2:
print("Tuesday");
break;
case 3:
print("Wednesday");
break;
case 4:
print("Thursday");
break;
case 5:
print("Friday");
break;
case 6:
print("Saturday");
break;
case 7:
print("Sunday");
break;
default:
print("Invalid day");
}
26. User Role Using switch
String role = "admin";
switch (role) {
case "admin":
print("Full access");
break;
case "manager":
print("Manager access");
break;
case "user":
print("Limited access");
break;
default:
print("Access denied");
}
27. Common Mistakes
Mistake 1: Using = Instead of ==
Use == when comparing values.
String role = "admin";
if (role == "admin") {
print("Admin");
}
Mistake 2: Incorrect Condition Order
Put more specific conditions before broader conditions when using an else-if ladder.
Mistake 3: Forgetting Braces
if (age >= 18) {
print("Adult");
} else {
print("Minor");
}
Mistake 4: Missing switch Cases
Always consider whether a default case or catch-all handling is appropriate for your switch logic.
28. Best Practices
- Use clear and meaningful conditions.
- Keep conditional logic simple and readable.
- Use
else-if when multiple ranges or conditions must be checked.
- Use
switch when comparing one value against multiple possible cases.
- Avoid unnecessarily deep nested
if statements.
- Order
else-if conditions carefully.
- Use braces consistently.
- Choose descriptive variable names.
- Test boundary values such as 0, minimum values, and maximum values.
29. Complete Example
void main() {
String role = "student";
int marks = 82;
if (role == "admin") {
print("Welcome Admin");
} else if (role == "teacher") {
print("Welcome Teacher");
} else if (role == "student") {
print("Welcome Student");
} else {
print("Unknown role");
}
if (marks >= 90) {
print("Grade A+");
} else if (marks >= 80) {
print("Grade A");
} else if (marks >= 70) {
print("Grade B");
} else if (marks >= 40) {
print("Pass");
} else {
print("Fail");
}
String menu = "profile";
switch (menu) {
case "home":
print("Home selected");
break;
case "profile":
print("Profile selected");
break;
case "settings":
print("Settings selected");
break;
default:
print("Invalid menu option");
}
}
30. Quick Revision
| Concept |
Purpose |
if |
Executes code when a condition is true |
else |
Executes when the if condition is false |
else if |
Checks additional conditions |
nested if |
Places one conditional statement inside another |
switch |
Matches a value against multiple cases |
default |
Handles unmatched switch cases |
31. Practice Exercises
- Write an
if statement to check whether a number is positive.
- Write an
if-else program to check whether a person is eligible to vote.
- Create an
else-if program to calculate student grades.
- Create an
else-if program for product discounts.
- Write a nested
if program for login and account status.
- Create a
switch program for selecting a menu option.
- Create a
switch program to display the day of the week.
- Create a Flutter example that displays different messages based on login status.
32. Key Takeaways
- if is used for a single condition.
- if-else provides two possible execution paths.
- else-if is useful for multiple conditions.
- Nested if allows conditions inside other conditions.
- switch is useful for matching one value against multiple cases.
- default handles unmatched switch cases.
- Conditional statements are fundamental to Dart programming and Flutter application logic.
33. Learn Flutter with JustAcademy
JustAcademy's Flutter training includes Dart programming fundamentals, including variables, data types, operators, control statements such as if, loops and switch, functions, OOP, collections, and asynchronous programming. :contentReference[oaicite:2]{index=2}
Explore the complete course:
JustAcademy Flutter Training
Register for a course demo:
JustAcademy Course Demo Registration